package cc.rengu.oltp.service.base;

import cc.rengu.oltp.service.common.constant.AppParamConstant;
import cc.rengu.oltp.service.common.constant.TreeNodeConstant;
import cc.rengu.oltp.service.common.enums.OltpRpcdEnum;
import cc.rengu.oltp.service.model.BizException;
import cc.rengu.oltp.service.model.TxnInfo;
import cc.rengu.oltp.service.realize.TxnInfoService;
import cc.rengu.oltp.service.realize.impl.TxnInfoServiceImpl;
import cc.rengu.oltp.utility.util.GlobalTransUtil;
import cc.rengu.oltp.utility.util.XmlTreeUtil;

import java.io.ByteArrayOutputStream;
import java.io.PrintWriter;

/**
 * 交易路由服务
 * Created by 王成 on 2017/6/27.
 */
public class TransRouteService extends RadpService {

    @Override
    protected int bizInit(String s) {
        return 0;
    }

    @Override
    protected int bizProcess(String s, int i) {
        try {
            XmlTreeUtil xmlTreeUtil = new XmlTreeUtil();
            /* 获取交易配置信息 */
            TxnInfo txnInfo = (TxnInfo) xmlTreeUtil.getXmlTreeObjectValue(TreeNodeConstant.TXN_INFO,TxnInfo.class);
            if (null == txnInfo) {
                TxnInfoService txnInfoService = new TxnInfoServiceImpl();
                txnInfo = txnInfoService.getCurrentTxnInfo();
                /* 将交易信息设置到交易缓存 */
                xmlTreeUtil.setXmlTreeObjectValue(TreeNodeConstant.TXN_INFO,txnInfo);
            }
            rglog.info("正在调用：<{}-{}>服务,服务名：{}", txnInfo.getSrcTxnAuthCfg().getTxnNum(),txnInfo.getSrcTxnAuthCfg().getTxnName(), txnInfo.getSrcTxnAuthCfg().getServiceName());
            return schedule.callService(txnInfo.getSrcTxnAuthCfg().getServiceName(), 0);
        } catch (Exception e) {
            XmlTreeUtil xmlTreeUtil = new XmlTreeUtil();
            ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
            e.printStackTrace(new PrintWriter(byteArrayOutputStream, true));
            rglog.error("交易路由服务异常，异常信息:<{}>", byteArrayOutputStream.toString());
            try {
                if (e instanceof BizException) {
                    xmlTreeUtil.setXmlTreeStringValue(TreeNodeConstant.RESP_CODE, ((BizException) e).getCode());
                    xmlTreeUtil.setXmlTreeStringValue(TreeNodeConstant.RESP_DESC, e.getMessage());
                } else {
                    xmlTreeUtil.setXmlTreeStringValue(TreeNodeConstant.RESP_CODE, OltpRpcdEnum.OLTP_PROCESS_ERROR.getRespCode());
                    xmlTreeUtil.setXmlTreeStringValue(TreeNodeConstant.RESP_DESC, OltpRpcdEnum.OLTP_PROCESS_ERROR.getRespDesc());
                }
            } catch (Exception ex) {
                byteArrayOutputStream = new ByteArrayOutputStream();
                e.printStackTrace(new PrintWriter(byteArrayOutputStream, true));
                rglog.error("设置异常错误码异常:<{}>", byteArrayOutputStream.toString());
            }
            return -1;
        }
    }

    @Override
    protected int bizTerminate(String s) {
        return 0;
    }
}
